<template>
  <el-dialog
    class="gl_dialog_TitleLine"
    width="980px"
    :title="title"
    :append-to-body="true"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-row v-loading="loading">
      <el-col :span="24">
        <el-steps :active="activeStep" align-center size="mini" process-status="finish" finish-status="success">
          <el-step title="选择赛制" />
          <el-step title="创建组别" />
        </el-steps>
      </el-col>
    </el-row>
    <div class="gl_py_20 edit_event_content">
      <el-form ref="categoryVO" :model="categoryVO" :rules="categoryVO_Rules" label-width="150px" size="mini" @submit.native.prevent>
        <template v-if="activeStep === 0">
          <!-- 选择赛制 -->
          <el-row :gutter="15">
            <el-col :span="24" class="form_item">
              <el-form-item label="项目名称" prop="name">
                <el-input  v-model.trim="categoryVO.name" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="8" class="form_item">
              <el-form-item label="项目限报人数">
                <el-select v-model="isMaxCompetitionRegisterCount" style="width: 100%;">
                  <el-option :key="false" :value="false" label="关闭" />
                  <el-option :key="true" :value="true" label="开启" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="isMaxCompetitionRegisterCount" :span="4" class="form_item">
              <el-input-number v-model="categoryVO.maxCompetitionRegisterCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="1" :max="99999" style="width:80%" />
            </el-col>
            <el-col :span="8" class="form_item">
              <el-form-item label="队伍子项限报人数" label-width="140px">
                <el-select v-model="isMaxDelegationPlayersCount" style="width: 100%;">
                  <el-option :key="false" :value="false" label="关闭" />
                  <el-option :key="true" :value="true" label="开启" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="isMaxDelegationPlayersCount" :span="4" class="form_item">
              <el-input-number v-model="categoryVO.maxDelegationPlayersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="1" :max="99999" style="width:80%" />
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="8" class="form_item">
              <el-form-item label="是否为赛事必选项目" prop="isLeagueRequired">
                <el-select v-model="categoryVO.isLeagueRequired" style="width: 100%;">
                  <el-option :value="true" label="是" />
                  <el-option :value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" class="form_item">
              <el-form-item label="是否为决赛资格项目" prop="isRelatedFinalQualification">
                <el-select v-model="categoryVO.isRelatedFinalQualification" style="width: 100%;">
                  <el-option :value="true" label="是" />
                  <el-option :value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="8" class="form_item">
              <el-form-item label="是否有脚套" prop="hasFootCover">
                <el-select v-model="categoryVO.hasFootCover" style="width: 100%;">
                  <el-option :value="true" label="是" />
                  <el-option :value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="categoryVO.hasFootCover" :span="8" class="form_item">
              <el-form-item label="是否允许自备" prop="canFootCoverSelfProvided">
                <el-select v-model="categoryVO.canFootCoverSelfProvided" style="width: 100%;">
                  <el-option :value="true" label="是" />
                  <el-option :value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="form_item">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content">注：该项目允许一个人报几项</div>
                <el-form-item label="" label-width="0" prop="maxEntry">
                  <el-select v-model="categoryVO.maxEntry" style="width: 100%;">
                    <el-option v-for="item in 25" :key="item" :value="item" :label="item + '项'" />
                  </el-select>
                </el-form-item>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="8" class="form_item">
              <el-form-item label="是否计入兼项" prop="isSimultaneous">
                <el-select v-model="categoryVO.isSimultaneous" style="width: 100%;">
                  <el-option :value="true" label="是" />
                  <el-option :value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="8" class="form_item">
              <el-form-item label="选择赛制" prop="eventFormatCode">
                <el-select v-model="categoryVO.eventFormatCode" placeholder="请选择赛制" style="width: 100%;" @change="ChangeEventFormatCode">
                  <el-option v-for="item in dict.eventFormat" :key="item.code" :value="item.code" :label="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="showRounds" :span="3" class="form_item">
              <el-form-item label="" label-width="0" prop="round">
                <el-select v-model="categoryVO.round" style="width: 100%;" @change="changeRound">
                  <el-option v-for="item in 4" :key="item" :value="item" :label="item + '轮'" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-for="(item, index) in categoryVO.categoryRounds" :key="index" :span="index == 0 ? 0 :4" class="form_item">
              <el-tooltip v-if="index != 0" class="item" effect="dark" placement="top">
                <div slot="content" style="width: 110px;">
                  第{{ index + 1 }}轮预赛晋级人数
                </div>
                <el-form-item label="" label-width="0">
                  <el-select v-model="categoryVO.categoryRounds[index].numberOfPromotions" filterable allow-create default-first-option :placeholder="`第${index + 1 }轮预赛晋级人数`" style="width: 100%;">
                    <el-option v-for="jtem in roundNums" :key="jtem" :value="jtem" :label="jtem" />
                  </el-select>
                </el-form-item>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col v-if="showRounds" :span="11" class="form_item">
              <el-form-item label="报名人数等于晋级人数是否需要进行预赛" label-width="270px" prop="isTrue">
                <el-select v-model="categoryVO.isPreliminary" :disabled="isDisabled" style="width: 100%;">
                  <el-option :value="true" label="是" />
                  <el-option :value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="showTeamMembersCount" class="gl_mb_20 gl_mx_30">
            <el-alert show-icon :closable="false" title="注意，删除最大人数视为无限制！" type="warning" />
          </div>
          <el-row :gutter="15">
            <el-col :span="8" class="form_item">
              <el-form-item label="项目类型" prop="preEventTypeCode">
                <template v-if="ImportId">
                  <template v-for="item in dict.preEventType">
                    <span v-if="item.code === categoryVO.preEventTypeCode" :key="item.code">{{ item.value.name }}</span>
                  </template>
                </template>
                <template v-else>
                  <el-select v-model="categoryVO.preEventTypeCode" placeholder="请选择项目类型" style="width: 100%;" @change="changePreEventTypeCode">
                    <el-option
                      v-for="item in dict.preEventType"
                      :key="item.code"
                      :value="item.code"
                      :label="item.value.name"
                    />
                  </el-select>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="form_item">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="width: 200px;">
                  重竞技的项目需要称重，非重竞技不需要
                </div>
                <el-form-item label="" label-width="0" prop="eventTypeCode">
                  <template v-if="ImportId">
                    <template v-for="item in dict.eventType">
                      <span v-if="item.code === categoryVO.eventTypeCode" :key="item.code">{{ item.value }}</span>
                    </template>
                  </template>
                  <template v-else>
                    <el-select v-model="categoryVO.eventTypeCode" :disabled="categoryVO.preEventTypeCode === 'CompetitiveTeam' || categoryVO.preEventTypeCode === 'MixedCompetitiveTeam'" placeholder="请选择项目类型" style="width: 100%;">
                      <el-option v-for="item in dict.eventType" :key="item.code" :value="item.code" :label="item.value" />
                    </el-select>
                  </template>
                </el-form-item>
              </el-tooltip>
            </el-col>
            <template v-if="showTeamMembersCount">
              <el-col :span="4" class="form_item">
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content" style="width: 200px;">
                    设置报名的参赛队最多能报多少队伍
                  </div>
                  <el-form-item label="" label-width="0" prop="maxDelegationTeamsCount">
                    <el-select v-model="categoryVO.maxDelegationTeamsCount" placeholder="" style="width: 100%;">
                      <el-option :value="null" label="无限制" />
                      <el-option v-for="item in 10" :key="item" :value="item" :label="item + '队'" />
                    </el-select>
                  </el-form-item>
                </el-tooltip>
              </el-col>
              <el-col :span="4" class="form_item">
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content" style="width: 200px;">
                    最低报名人数
                  </div>
                  <el-form-item label="" label-width="0" prop="minTeamMembersCount">
                    <!-- 混双的情况 -->
                    <el-input-number v-if="categoryVO.preEventTypeCode === 'MixedDouble'" v-model="categoryVO.minTeamMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="2" :max="2" style="margin-right: 5px" />
                    <!-- 双人的情况 -->
                    <el-input-number v-else-if="registerCodeIsD" v-model="categoryVO.minTeamMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="2" style="margin-right: 5px" />
                    <!-- 其他 -->
                    <el-input-number v-else v-model="categoryVO.minTeamMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="0" style="margin-right: 5px" />
                  </el-form-item>
                </el-tooltip>
              </el-col>
              <el-col :span="4" class="form_item">
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content" style="width: 200px;">
                    最高报名人数
                  </div>
                  <el-form-item label="" label-width="0" prop="maxTeamMembersCount">
                    <!-- 混双的情况 -->
                    <el-input-number v-if="categoryVO.preEventTypeCode === 'MixedDouble'" v-model="categoryVO.maxTeamMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="2" :max="2" style="margin-right: 5px" />
                    <!-- 双人的情况 -->
                    <el-input-number v-else-if="registerCodeIsD" v-model="categoryVO.maxTeamMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="2" style="margin-right: 5px" />
                    <!-- 团体竞技和混合团体竞技时 -->
                    <el-input-number v-else-if="categoryVO.preEventTypeCode === 'CompetitiveTeam' || categoryVO.preEventTypeCode === 'MixedCompetitiveTeam'" v-model="categoryVO.maxTeamMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="1" :max="10" style="margin-right: 5px" />
                    <!-- 其他 -->
                    <el-input-number v-else v-model="categoryVO.maxTeamMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="1" style="margin-right: 5px" />
                  </el-form-item>
                </el-tooltip>
              </el-col>
            </template>
          </el-row>
          <el-row v-if="categoryVO.preEventTypeCode === 'MixedTeam' || categoryVO.preEventTypeCode === 'MixedCompetitiveTeam'" :gutter="15">
            <el-col :span="8" class="form_item">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="width: 150px;">
                  男性最小人数
                </div>
                <el-form-item label="男性人数" prop="teamMinMaleMembersCount">
                  <el-input-number v-model="categoryVO.teamMinMaleMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="0" style="margin-right: 5px" />
                  <!-- <el-select v-model="categoryVO.teamMinMaleMembersCount" clearable placeholder="男性最小人数" style="width: 100%;">
                    <template>
                      <el-option v-for="item in 10" :key="item" :value="item" :label="item" />
                    </template>
                  </el-select> -->
                </el-form-item>
              </el-tooltip>
            </el-col>
            <el-col :span="1" class="form_item" style="width:10px;padding:0px;text-align: center;">
              <span style="display: inline-block;padding-top: 5px;">-</span>
            </el-col>
            <el-col :span="4" class="form_item">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="width: 150px;">
                  男性最大人数
                </div>
                <el-form-item label="" label-width="0" prop="teamMaxMaleMembersCount">
                  <el-input-number v-model="categoryVO.teamMaxMaleMembersCount" :precision="0" placeholder="不限制" size="mini" controls-position="right" :min="0" style="margin-right: 5px" />
                  <!-- <el-select v-model="categoryVO.teamMaxMaleMembersCount" clearable placeholder="男性最大人数" style="width: 100%;">
                    <template>
                      <el-option v-for="item in 10" :key="item" :value="item" :label="item" />
                    </template>
                  </el-select> -->
                </el-form-item>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row v-if="categoryVO.preEventTypeCode === 'MixedTeam' || categoryVO.preEventTypeCode === 'MixedCompetitiveTeam'" :gutter="15">
            <el-col :span="8" class="form_item">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="width: 150px;">
                  女性最小人数
                </div>
                <el-form-item label="女性人数" prop="teamMinFemaleMembersCount">
                  <el-input-number v-model="categoryVO.teamMinFemaleMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="0" style="margin-right: 5px" />
                  <!-- <el-select v-model="categoryVO.teamMinFemaleMembersCount" clearable placeholder="女性最小人数" style="width: 100%;">
                    <template>
                      <el-option v-for="item in 10" :key="item" :value="item" :label="item" />
                    </template>
                  </el-select> -->
                </el-form-item>
              </el-tooltip>
            </el-col>
            <el-col :span="1" class="form_item" style="width:10px;padding:0px;text-align: center;">
              <span style="display: inline-block;padding-top: 5px;">-</span>
            </el-col>
            <el-col :span="4" class="form_item">
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="width: 150px;">
                  女性最大人数
                </div>
                <el-form-item label="" label-width="0" prop="teamMaxFemaleMembersCount">
                  <el-input-number v-model="categoryVO.teamMaxFemaleMembersCount" :precision="0" placeholder="不限制" size="mini" controls-position="right" :min="0" style="margin-right: 5px" />
                  <!-- <el-select v-model="categoryVO.teamMaxFemaleMembersCount" clearable placeholder="女性最大人数" style="width: 100%;">
                    <template>
                      <el-option v-for="item in 10" :key="item" :value="item" :label="item" />
                    </template>
                  </el-select> -->
                </el-form-item>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row v-if="categoryVO.registerTypeCode === 'T'" :gutter="15">
            <el-col :span="8" class="form_item is_big_team">
              <el-form-item label="是否为大团体项目">
                <el-select v-model="categoryVO.isBigTeam" placeholder="请选择是否为大团体项目" style="width: 100%;">
                  <el-option :value="true" label="是" />
                  <el-option :value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="categoryVO.eventTypeCode === 'NoneCompetitive'" :gutter="15">
            <el-col :span="8" class="form_item">
              <el-tooltip class="item" effect="dark" content="设置为有组别，可设置子项" placement="top">
                <el-form-item label="有无组别">
                  <template v-if="ImportId">
                    <span>{{ categoryVO.hasGroup && '有组别' || '无组别' }}</span>
                  </template>
                  <template v-else>
                    <el-select v-model="categoryVO.hasGroup" placeholder="请选择有无组别" style="width: 100%;">
                      <el-option :value="true" label="有组别" />
                      <el-option :value="false" label="无组别" />
                    </el-select>
                  </template>
                </el-form-item>
              </el-tooltip>
            </el-col>
          </el-row>
        </template>
      </el-form>
      <!-- 创建组别 -->
      <template v-if="activeStep === 1">
        <el-row v-for="(item, index) in categoryDTO.eventGroups" :key="index" :gutter="15">
          <el-col :span="19">
            <event-group-template :ref="'eventGroupTemplate_' + index" :key="index" :event-group="item" :category="categoryVO" />
          </el-col>
          <el-col :span="5" style="position: absolute;bottom: 19px;right: 0;">
            <el-button v-if="categoryDTO.eventGroups.length !== 1" type="danger" size="mini" icon="el-icon-close" @click="deleteEventGroup(index)">删除</el-button>
            <el-button v-if="index === categoryDTO.eventGroups.length - 1" type="default" size="mini" icon="el-icon-plus" @click="addEventGroup(index)">组别</el-button>
          </el-col>
        </el-row>
      </template>
    </div>
    <el-row>
      <el-col :span="24" align="right">
        <el-button v-if="showPrevBtn" type="default" size="mini" @click="prevStep()">上一步</el-button>
        <el-button v-if="showCommitBtn" type="primary" size="mini" @click="submitEventInfo()">提交</el-button>
        <el-button v-if="showNextBtn" type="default" size="mini" @click="nextStep()">下一步</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
/**
 * （1）混合和非混合
 *  -- 混合 无具体的男女级别 只有级别
 *  -- 非混合 男女级别
 * （2）重竞技和非重竞技
 *  -- 重竞技 必须有级别
 *  -- 非重 可以选择
 **/
import validator from '@/lib/validate/index.js';
import { mapState, mapActions } from 'vuex';
import { SiSTKWEventsManagementCategoryCreateDto, SiSTKWEventsManagementEventGroupDto } from '@/lib/form/game/swaggerForm';
import { SiSTKWEventsManagementCategoryCreateDTO_Rules, SiSTKWEventsManagementEventGroupDTO_Rules } from '@/lib/validate/events';
import {
  api_POST_EventsManagementCategory
} from '@/extend/api/gameswaggerApi/app';
import eventGroupTemplate from './eventGroupTemplate';
import { CopyData } from '@/lib';
export default {
  name: 'AddEvent',
  components: {
    eventGroupTemplate
  },
  data() {
    return {
      loading: false,
      title: '添加项目',
      dialogVisible: false,
      categoryVO: new SiSTKWEventsManagementCategoryCreateDto(),
      categoryDTO: {
        eventGroups: [{}]
      },
      categoryVO_Rules: new SiSTKWEventsManagementCategoryCreateDTO_Rules(),
      // 组别
      eventGroupsVO: new SiSTKWEventsManagementEventGroupDto(),
      eventGroupsVO_Rules: new SiSTKWEventsManagementEventGroupDTO_Rules(),
      activeStep: 0,
      // 年龄区间
      gameEventAge: [],
      // 团体是否显示人员数量编辑
      showTeamMembersCount: false,
      // 打分制显示轮次
      showRounds: false,
      // 项目类型是否为双人
      registerCodeIsD: false,
      // 项目类型是否为混合
      registerCodeIsX: false,
      roundNums: [2, 4, 8, 16, 32, 64],
      // 是否可选择
      isDisabled: false,
      // 是否可提交
      isSubmit: false,
      errorText: '',
      ImportId: '', // 存在id的话，表示是导入模板进入的，用于判断是否可编辑
      isMaxCompetitionRegisterCount: false,
      isMaxDelegationPlayersCount: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    }),
    showPrevBtn: function() {
      return this.activeStep === 1;
    },
    showCommitBtn: function() {
      return this.activeStep === 1;
    },
    showNextBtn: function() {
      return this.activeStep === 0;
    }
  },
  watch: {
    // 是否有脚套
    'categoryVO.hasFootCover': function() {
      this.categoryVO.canFootCoverSelfProvided = false;
    },
    // 项目类型 (个人、团体) 团体、双人需要显示人数限制
    'categoryVO.registerTypeCode': function(val) {
      if (val && val === 'D') { // 双人
        this.categoryVO.minTeamMembersCount = 2;
        this.categoryVO.maxTeamMembersCount = 2;
        this.showTeamMembersCount = true;
        this.registerCodeIsD = true;
        this.categoryVO.isBigTeam = false;
      } else if (val && val === 'T') { // 团体
        this.showTeamMembersCount = true;
        this.registerCodeIsD = false;
        this.categoryVO.isBigTeam = true;
      } else {
        // this.categoryVO.maxDelegationPlayersCount = null;
        this.categoryVO.minTeamMembersCount = 1;
        this.categoryVO.maxTeamMembersCount = 1;
        this.showTeamMembersCount = false;
        this.registerCodeIsD = false;
        this.categoryVO.isBigTeam = false;
      }
    },
    // 项目类型 (重竞技、非重竞技)
    'categoryVO.eventTypeCode': function(val) {
      // 重竞技 一定有组别
      if (val !== 'NoneCompetitive') {
        this.categoryVO.hasGroup = true;
      }
    },
    // 选择赛制
    'categoryVO.eventFormatCode': function(val) {
      if (val === 'Score' || val === 'DualScore') {
        this.showRounds = true;
      } else {
        this.showRounds = false;
      }
    },
    // 显示项目类型
    // 'categoryVO.preEventTypeCode': function(val) {
    //   // 混合团体eventTypeCode
    //   this.categoryVO.teamMinMaleMembersCount = undefined; // undefined 可以使InputNumber数字控件 显示为空
    //   this.categoryVO.teamMaxMaleMembersCount = undefined;
    //   this.categoryVO.teamMinFemaleMembersCount = undefined;
    //   this.categoryVO.teamMaxFemaleMembersCount = undefined;
    //   this.categoryVO.eventTypeCode = 'Competitive';
    //   if (!val) {
    //     this.categoryVO.registerTypeCode = '';
    //     this.categoryVO.genderCode = '';
    //     return;
    //   }
    //   for (let i = 0; i < this.dict.preEventType.length; i++) {
    //     const item = this.dict.preEventType[i];
    //     if (item.code === val) {
    //       this.categoryVO.registerTypeCode = item.value.registerTypeCode;
    //       this.categoryVO.genderCode = item.value.genderCode;
    //       break;
    //     }
    //   }
    // },
    // 根据轮次数量处理数据
    // 'categoryVO.round': {
    //   handler(val) {
    //     this.categoryVO.categoryRounds = [];
    //     for (let i = 0; i < val; i++) {
    //       const obj = {
    //         id: null,
    //         round: i + 1,
    //         numberOfPromotions: null
    //       };
    //       this.categoryVO.categoryRounds.push(obj);
    //     }
    //     if (val === 1) {
    //       this.categoryVO.isPreliminary = false;
    //       this.isDisabled = true;
    //     } else {
    //       this.categoryVO.isPreliminary = true;
    //       this.isDisabled = false;
    //     }
    //   },
    //   immediate: true
    // },
    // 根据轮次人数数量处理数据
    'categoryVO.categoryRounds': {
      handler(value) {
        this.isSubmit = true;
        if (value[2] && value[2].numberOfPromotions && value[1].numberOfPromotions >= value[2].numberOfPromotions) {
          this.$message({
            duration: 15000,
            showClose: true,
            message: '第2轮晋级人数必须小于第3轮晋级人数',
            type: 'error'
          });
          this.isSubmit = false;
          this.errorText = '第2轮晋级人数必须小于第3轮晋级人数';
        }
        if (value[3] && value[3].numberOfPromotions && value[2].numberOfPromotions >= value[3].numberOfPromotions) {
          this.$message({
            duration: 15000,
            showClose: true,
            message: '第3轮晋级人数必须小于第4轮晋级人数',
            type: 'error'
          });
          this.isSubmit = false;
          this.errorText = '第3轮晋级人数必须小于第4轮晋级人数';
        }
      },
      deep: true
    },
    // 项目限报人数
    isMaxCompetitionRegisterCount: function(val) {
      const _this = this;
      if (val) {
        _this.categoryVO.maxCompetitionRegisterCount = _this.categoryDTO.maxCompetitionRegisterCount || 1;
      } else {
        _this.categoryVO.maxCompetitionRegisterCount = null;
      }
    },
    // 队伍子项限报人数
    isMaxDelegationPlayersCount: function(val) {
      if (val) {
        this.categoryVO.maxDelegationPlayersCount = this.categoryDTO.maxDelegationPlayersCount || 1;
      } else {
        this.categoryVO.maxDelegationPlayersCount = null;
      }
    }
  },
  created() {
    this.gameId = this.$route.params.parentId;
    this.getDict();
    // 先不验证最大最小人数限制
    this.initRule();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    changePreEventTypeCode(val) {
      // 混合团体eventTypeCode
      this.categoryVO.teamMinMaleMembersCount = undefined; // undefined 可以使InputNumber数字控件 显示为空
      this.categoryVO.teamMaxMaleMembersCount = undefined;
      this.categoryVO.teamMinFemaleMembersCount = undefined;
      this.categoryVO.teamMaxFemaleMembersCount = undefined;
      if (this.categoryVO.registerTypeCode === 'T') {
        this.categoryVO.minTeamMembersCount = 1;
        this.categoryVO.maxTeamMembersCount = 1;
      }
      this.categoryVO.eventTypeCode = 'Competitive';
      if (!val) {
        this.categoryVO.registerTypeCode = '';
        this.categoryVO.genderCode = '';
        return;
      }
      for (let i = 0; i < this.dict.preEventType.length; i++) {
        const item = this.dict.preEventType[i];
        if (item.code === val) {
          this.categoryVO.registerTypeCode = item.value.registerTypeCode;
          this.categoryVO.genderCode = item.value.genderCode;
          break;
        }
      }
      if (this.categoryVO.registerTypeCode === 'T') {
        this.categoryVO.minTeamMembersCount = 1;
        this.categoryVO.maxTeamMembersCount = 1;
      }
    },
    ChangeEventFormatCode(val) {
      // 重竞技 一定有组别
      if (val === 'Score' || val === 'DualScore') {
        this.showRounds = true;
        this.categoryVO.round = 1;
      } else {
        this.showRounds = false;
        this.categoryVO.round = 0;
        this.categoryVO.categoryRounds = [];
      }
      this.changeRound(this.categoryVO.round);
    },
    changeRound(val) {
      this.categoryVO.categoryRounds = [];
      for (let i = 0; i < val; i++) {
        const obj = {
          id: null,
          round: i + 1,
          numberOfPromotions: null
        };
        this.categoryVO.categoryRounds.push(obj);
        if (val === 1) {
          this.categoryVO.isPreliminary = false;
          this.isDisabled = true;
        } else {
          this.categoryVO.isPreliminary = true;
          this.isDisabled = false;
        }
      }
    },
    // 初始化
    init(categoryInfo) {
      this.activeStep = 0;
      this.categoryDTO = categoryInfo || { eventGroups: [{}] };
      this.categoryVO = new SiSTKWEventsManagementCategoryCreateDto();
      this.eventGroupsVO = new SiSTKWEventsManagementEventGroupDto();
      if (categoryInfo) {
        CopyData(categoryInfo, this.categoryVO);
        // 排序_sortObj
        this.categoryVO.categoryRounds.sort((a, b) => a.round - b.round);
        this.categoryVO.teamMinMaleMembersCount = this.categoryVO.teamMinMaleMembersCount ? this.categoryVO.teamMinMaleMembersCount : undefined;
        this.categoryVO.teamMaxMaleMembersCount = this.categoryVO.teamMaxMaleMembersCount ? this.categoryVO.teamMaxMaleMembersCount : undefined;
        this.categoryVO.teamMinFemaleMembersCount = this.categoryVO.teamMinFemaleMembersCount ? this.categoryVO.teamMinFemaleMembersCount : undefined;
        this.categoryVO.teamMaxFemaleMembersCount = this.categoryVO.teamMaxFemaleMembersCount ? this.categoryVO.teamMaxFemaleMembersCount : undefined;
        if (this.categoryVO.round === 1) {
          this.isDisabled = true;
        } else {
          this.isDisabled = false;
        }
        console.log(this.categoryVO);
      } else {
        this.gameEventAge = [];
        this.categoryVO.hasGroup = true;
        this.categoryVO.during = 0;
        this.categoryVO.maxEntry = 1;
        this.categoryVO.genderCode = '';
        this.categoryVO.maxDelegationTeamsCount = null;
        this.categoryVO.minTeamMembersCount = 1;
        this.categoryVO.maxTeamMembersCount = 1;
        this.categoryVO.teamMinMaleMembersCount = undefined; // undefined 可以使InputNumber数字控件 显示为空
        this.categoryVO.teamMaxMaleMembersCount = undefined;
        this.categoryVO.teamMinFemaleMembersCount = undefined;
        this.categoryVO.teamMaxFemaleMembersCount = undefined;
        this.categoryVO.isBigTeam = false;
        this.categoryVO.eventTypeCode = 'Competitive';
        this.showTeamMembersCount = false;
      }
      this.isMaxCompetitionRegisterCount = !!this.categoryVO.maxCompetitionRegisterCount;
      this.isMaxDelegationPlayersCount = !!this.categoryVO.maxDelegationPlayersCount;
    },
    initRule() {
      // 团体设置人数限制
      const _this = this;
      this.categoryVO_Rules.minTeamMembersCount = [
        validator.required('最低报名人数不能为空'),
        {
          validator(rule, value, callback) {
            if (value && _this.categoryVO.maxTeamMembersCount && value > _this.categoryVO.maxTeamMembersCount) {
              callback(new Error('最低报名人数应小于最大报名人数'));
            }
            // const _teamMinMaleMembersCount = _this.categoryVO.teamMinMaleMembersCount;
            // const _teamMinFemaleMembersCount = _this.categoryVO.teamMinFemaleMembersCount;
            // const _sum = (_teamMinMaleMembersCount ? Number(_teamMinMaleMembersCount) : 0) + (_teamMinFemaleMembersCount ? Number(_teamMinFemaleMembersCount) : 0);
            // 如果设置了男性或者女性人数，那么最低报名人数应为男性最少人数 + 女性最少人数
            // if (_teamMinMaleMembersCount != null && _teamMinFemaleMembersCount != null && value !== _sum) {
            //   callback(new Error('最低报名人数应等于男性最小人数和女性最小人数之和'));
            // }
            callback();
          },
          trigger: 'change'
        }];
      this.categoryVO_Rules.maxTeamMembersCount = [
        validator.required('最大报名人数不能为空'),
        {
          validator(rule, value, callback) {
            if (value && _this.categoryVO.minTeamMembersCount && value < _this.categoryVO.minTeamMembersCount) {
              callback(new Error('最大报名人数应大于最低报名人数'));
            }
            // const _teamMaxMaleMembersCount = _this.categoryVO.teamMaxMaleMembersCount;
            // const _teamMaxFemaleMembersCount = _this.categoryVO.teamMaxFemaleMembersCount;
            // const _sum = (_teamMaxMaleMembersCount ? Number(_teamMaxMaleMembersCount) : 0) + (_teamMaxFemaleMembersCount ? Number(_teamMaxFemaleMembersCount) : 0);
            // 如果设置了男性或者女性人数，那么最大报名人数应为男性最大 + 女性最大
            // if (_teamMaxMaleMembersCount != null && _teamMaxFemaleMembersCount != null && value > _sum && value != null) {
            //   callback(new Error('最高报名人数应小于等于男性最大人数和女性最大人数之和'));
            // }
            callback();
          },
          trigger: 'change'
        }
      ];
      // TODO
      // this.categoryVO_Rules.categoryRounds = [{
      //   validator(rule, value, callback) {
      //     if (value[2] && value[2].numberOfPromotions && value[1].numberOfPromotions >= value[2].numberOfPromotions) {
      //       callback(new Error('第2轮晋级人数必须小于第3轮晋级人数'));
      //     }
      //     if (value[3] && value[3].numberOfPromotions && value[2].numberOfPromotions >= value[3].numberOfPromotions) {
      //       callback(new Error('第3轮晋级人数必须小于第4轮晋级人数'));
      //     }
      //     callback();
      //   },
      //   trigger: 'change'
      // }];
    },
    // changemixTeam (val) {
    //   this.categoryVO.minTeamMembersCount = !val ? 10 : val;
    //   console.log(this.categoryVO.minTeamMembersCount);
    // },
    // changemaxTeam (val) {
    //   this.categoryVO.maxTeamMembersCount = !val ? 10 : val;
    //   console.log(this.categoryVO.maxTeamMembersCount);
    // },
    open(categoryInfo) {
      this.ImportId = categoryInfo && categoryInfo.id || '';
      this.init(categoryInfo);
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.categoryVO && this.$refs.categoryVO.clearValidate();
        this.$refs.eventGroupsVO && this.$refs.eventGroupsVO.clearValidate();
      });
    },
    prevStep() {
      this.activeStep--;
    },
    nextStep() {
      this.$refs.categoryVO.validate(valid => {
        console.log(this.categoryVO);
        if (!valid) return;
        // 轮次人数不能为空的提示
        for (let i = 0; i < this.categoryVO.categoryRounds.length; i++) {
          const item = this.categoryVO.categoryRounds[i];
          if (!item.numberOfPromotions && item.round !== 1) {
            this.$message({
              duration: 10000,
              showClose: true,
              message: `第${item.round}轮晋级人数不能为空`,
              type: 'error'
            });
            return;
          }
        }
        if (!this.isSubmit) {
          this.$message({
            duration: 10000,
            showClose: true,
            message: this.errorText,
            type: 'error'
          });
          return;
        }
        this.activeStep++;
        // 格式化男性、女性数据格式
        // this.categoryVO.teamMinMaleMembersCount = this.categoryVO.teamMinMaleMembersCount ? this.categoryVO.teamMinMaleMembersCount : null;
        // this.categoryVO.teamMaxMaleMembersCount = this.categoryVO.teamMaxMaleMembersCount ? this.categoryVO.teamMaxMaleMembersCount : null;
        // this.categoryVO.teamMinFemaleMembersCount = this.categoryVO.teamMinFemaleMembersCount ? this.categoryVO.teamMinFemaleMembersCount : null;
        // this.categoryVO.teamMaxFemaleMembersCount = this.categoryVO.teamMaxFemaleMembersCount ? this.categoryVO.teamMaxFemaleMembersCount : null;
      });
    },
    submitEventInfo() {
      if (!this.categoryDTO || !this.categoryDTO.eventGroups.length) {
        this.$refs.eventGroupTemplate.submitGroupInfo().then(eventGroupsVO => {
          this.categoryVO.eventGroups = [eventGroupsVO];
          this.categoryVO.competitionId = this.gameId;
          this.createEventCategory();
        });
      } else {
        const _promiseList = [];
        for (let i = 0; i < this.categoryDTO.eventGroups.length; i++) {
          _promiseList.push(this.$refs['eventGroupTemplate_' + i][0].submitGroupInfo());
        }
        Promise.all(_promiseList).then(eventGroups => {
          this.categoryVO.eventGroups = eventGroups;
          this.categoryVO.competitionId = this.gameId;
          this.createEventCategory();
        });
      }
    },
    // 创建项目类别
    createEventCategory() {
      console.log('this.categoryVO', this.categoryVO);
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_POST_EventsManagementCategory(this.categoryVO).then(res => {
          this.$message({ type: 'success', message: '新增成功！' });
          this.init();
          this.loading = false;
          this.$emit('refreshPage');
          this.dialogVisible = false;
          resolve(res);
        }, error => {
          this.loading = false;
          this.$message({ type: 'error', message: '新增失败！' + (error.error.details || error.error.message) });
          reject(error);
        });
      });
    },
    // 删除组别
    deleteEventGroup(index) {
      const _promiseList = [];
      for (let i = 0; i < this.categoryDTO.eventGroups.length; i++) {
        _promiseList.push(this.$refs['eventGroupTemplate_' + i][0].calcGroupInfo());
      }
      Promise.all(_promiseList).then(eventGroups => {
        this.categoryDTO.eventGroups = eventGroups;
        this.categoryDTO.eventGroups.splice(index, 1);
      });
    },
    // 新增组别
    addEventGroup(index) {
      this.categoryDTO.eventGroups.push({});
    }
  }
};
</script>
<style>
.edit_event_content {
  width: 860px;
  min-height: 280px;
  margin: 0 auto;
}
.is_big_team .el-form-item--mini .el-form-item__label {
  line-height: 14px;
}
</style>
